import json

from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from django.http import JsonResponse
from .models import Book,Category
def cxcj(request,id):
    # 使用get方法
    if request.method=="GET":
        # 调用Book里面的方法
        # all_data=Book.objects.all()
        # # 每页10行
        # page_size=request.GET.get("page_size")or 10
        # # 查看第一页
        # page=request.GET.get("page",1)
        # # 调用实现分页的
        # l=Paginator(all_data,page_size)
        # table_all=l.get_page(page)
        # 使用list储存
        category=Category.objects.get(id=id)
        books=category.children1.all()
        list=[]
        # 循环打印
        for intem in books:
            # 储存在这个列表里把内容
            list.append({
                "name":intem.name,
                "categoryid_id":intem.categoryid_id,
                "status":intem.status,
                "description":intem.description,
                "created_at":intem.created_at,
                "grade":intem.grade
            })
            # 打印数据和查看数据是否打印成功
        return JsonResponse({"message":"查询成功","data":list})
        # 使用POST方法创建
    # elif request.method=="POST":
    #     # 使用json调用
    #     data=json.loads(request.body)
    #
    #     name=data["name"]
    #     categoryid_id=data["categoryid_id"]
    #     status=data["status"]
    #     description=data["description"]
    #     created_at=data["created_at"]
    #     grade=data["grade"]
    #     # 创建的内容
    #     create=Book.objects.create(
    #         name=name,
    #         categoryid_id=categoryid_id,
    #         status=status,
    #         description=description,
    #         created_at=created_at,
    #         grade=grade
    #     )
    # # 直接打印在json里
    # create_data=model_to_dict(create)
    # # 查看数据是否能够创建成功
    # return JsonResponse({"message":"添加成功","data":create_data})

def delete(request,id):

    if request.method=="DELETE":
        Book.objects.get(id=id).delete()
    return JsonResponse({"delete":"删除成功"})




